package jdbclearn2;
/*
@Date:2025/3/12
*/

import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;

public class jdbcLearn2 {
    public static void main(String[] args) throws Exception {

        System.out.println(findAll());
    }
    @Test
    public void isAdmin() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "123456";
        final Connection connection = DriverManager.getConnection(url, username, password);
        String user = "aaa";
        String pwd = "q3313ws";
        String sql = "select* from tb_user where username=? and password=?";
        final PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //设置？的值
        preparedStatement.setString(1, user);
        preparedStatement.setString(2, pwd);
        final ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            System.out.println("登陆成功");
        } else {
            System.out.println("非法管理员");
        }

    }

    @Test
    public void inset() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        String user = "aaa";
        String pwd = "123456";
        String sql = "insert into tb_user values(null,?,?)";
        PreparedStatement prestatement = connection.prepareStatement(sql);
        //设置？的值
        prestatement.setString(1, user);
        prestatement.setString(2, pwd);
        int i = prestatement.executeUpdate();
        System.out.println(i + "行数据添加");
    }

    @Test
    public static ArrayList<User> findAll() throws Exception {
        final ArrayList<User> users = new ArrayList<>();
        String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "123456";
        final Connection connection = DriverManager.getConnection(url, username, password);
        String sql = " select* from tb_user";
        final PreparedStatement prestatement = connection.prepareStatement(sql);
        final ResultSet resultSet = prestatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String username1 = resultSet.getString("username");
            String password1 = resultSet.getString("username");
            User user = new User();
            user.setId(id);
            user.setUser(username1);
            user.setPassword(password1);
            users.add(user);
        }
        prestatement.close();
        connection.close();
        return users;
    }
}
